<?php

namespace App\Services\Infra;

use App\Facades\DeviceManager as ForeignDeviceManager;
use App\Models\AdminInfo;
use App\Models\AfterService;
use App\Models\User;
use App\Models\UserInfo;
use App\Exceptions\UserException;
use DB;
use Exception;
use Illuminate\Database\QueryException;
use Sentinel;

class UserManager
{
    /**
     * 增加用户信息
     * @param array $data [用户信息数据]
     */
    public function addUserInfo($data)
    {
        try{
            UserInfo::create($data);
        }catch(Exception $e){
            throw new UserException('info.add');
        }
    }

    /**
     * 更新用户信息
     * @param  integer $userId 
     * @param  array $data   
     * @return          
     */
    public function updateUserInfo($userId, $data)
    {
        try{
            $userInfo = UserInfo::where('user_id', $userId)->first();
            if(is_null($userInfo)){
                throw new UserException('info.notFound');
            }
            return $userInfo->update($data);
        }catch(UserException $e){
            throw $e;
        }catch(Exception $e){
            throw new UserException('info.update');
        }
    }

    /**
     * 获取用户
     * @return 
     */
    public function getUser()
    {
    	$user = Sentinel::getUser();
        
        if(is_null($user))
        {
            throw new UserException('notFound');
        }
        
	    return $user;
    }

    /**
     * 根据 openId 获取用户
     * @param  string $openId 
     * @return          
     */
    public function getUserInfoByOpenId($openId)
    {
        return UserInfo::where('open_id', $openId)->first();
    }

    /**
     * 根据用户 id 获取用户信息
     * @param  integer $userId 
     * @param  array $select 
     * @return          
     */
    public function getUserInfoByUserId($userId, $select = null)
    {
        $query = UserInfo::where('user_id', $userId);
        if(!is_null($select)){
            $query->select($select);
        }
        return $query->first();
    }

    /**
     * 添加售后服务
     * @param array $data 
     */
    public function addAfterService($data)
    {
        try{
            AfterService::create($data);
        }catch(Exception $e){
            throw new UserException('afterService.add');
        }
    }

    /**
     * 添加管理员信息
     * @param array $data 
     */
    public function addAdminInfo($data)
    {
        AdminInfo::create($data);
    }

    /**
     * 根据 id 获取用户
     * @param  integer $id 
     * @return      
     */
    public function getUserById($id)
    {
        $user = User::where('id', $id)->first();
        if(is_null($user))
        {
            throw new UserException('adminInfo.notFound');
        }
        
        return $user;
    }

    /**
     * 获取全部管理员并带有管理员信息和角色名
     * @return  
     */
    public function getAllAdminWithInfoAndRoleName()
    {
        return AdminInfo::with(['user' => function($query){
            $query->with(['roles' => function($query){
                $query->select('id', 'name');
            }])->select('id', 'username');
        }])->paginate(15);
    }

    /**
     * 获取用户信息 builder
     * @param  string $condition 
     * @param  string $column    
     * @return             
     */
    public function findUserInfoBuilder($condition, $column = null)
    {
        $query = UserInfo::select($column);
        if(!empty($condition)){
           $query->where('name', 'like', '%'.$condition.'%')->orWhere('phone', 'like', '%'.$condition.'%');
        }
        return $query;
    }

    /**
     * 根据设备码获取售后服务 builder
     * @param  string  $condition 
     * @param  array $deviceIds  
     * @return              
     */
    public function getAfterServiceListBuilderByDeviceIds($condition, $deviceIds)
    {
        $query = AfterService::orderBy('status')->latest();
        if(!empty($condition)){
            $query->whereIn('device_id', $deviceIds);
        }
        return $query;
    }

    /**
     * 根据 id 用户 售后服务
     * @param integer  $id 
     * @return      
     */
    public function getAfterServiceListById($id)
    {
        $afterService = AfterService::where('id', $id)->first();
        if(is_null($afterService)){
            throw new UserException('afterService.notFound');
        }
        return $afterService;
    }

    /**
     * 根据状态对售后服务进行计数
     * @param  integer $status 
     * @return          
     */
    public function countAfterServiceListByStatus($status)
    {
        return AfterService::where('status', $status)->count();
    }

    public function getUserInfoByDeviceCode($deviceCode)
    {
        $device = ForeignDeviceManager::getDeviceByQuery('code', $deviceCode);
        $device->load(['userInfos' => function($query){
            $query->select(['current_device_id', 'open_id']);
        }]);
        return $device->userInfos;
    }

}
